import React, { useState, useEffect, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import api from '../utils/api';
import { RequestError } from '../utils/request';
import { uploadCoverImage, uploadPosterImage, uploadVideo } from '../utils/oss';
import { userStorage } from '../utils/storage';
import UploadDialog from '../components/UploadDialog';
import './UploadCourse.css';

function UploadCourse() {
  const navigate = useNavigate();
  const location = useLocation();
  const [courseData, setCourseData] = useState(null);
  const prevCourseDataRef = useRef(null); // 用于跟踪上一次的课程数据
  const videosRef = useRef([]); // 用于存储视频列表的引用，便于清理
  const previewVideoRef = useRef(null); // 用于存储预览视频的引用，便于清理
  const [coverImage, setCoverImage] = useState(null);
  const [coverPreview, setCoverPreview] = useState('');
  const [posterImage, setPosterImage] = useState(null);
  const [posterPreview, setPosterPreview] = useState('');
  const [videos, setVideos] = useState([]);
  const [uploading, setUploading] = useState(false);
  const [previewVideo, setPreviewVideo] = useState(null); // 当前预览的视频
  const [draggedIndex, setDraggedIndex] = useState(null); // 正在拖拽的视频索引
  
  // 上传进度状态
  const [uploadDialogVisible, setUploadDialogVisible] = useState(false);
  const [currentTask, setCurrentTask] = useState('');
  const [taskProgress, setTaskProgress] = useState(0);
  const [totalTasks, setTotalTasks] = useState(0);
  const [completedTasks, setCompletedTasks] = useState(0);
  
  // 已上传文件的 OSS 路径（用于接口重试）
  const [uploadedPaths, setUploadedPaths] = useState({
    coverPath: '',
    posterPath: '',
    videoPaths: []
  });
  const [uploadPhase, setUploadPhase] = useState('idle'); // idle | uploading | uploaded | updating | success | error

  // 重置所有状态的函数
  const resetAllStates = () => {
    console.log('执行状态重置 - 清理所有数据和状态');
    
    // 先清理预览URL（避免内存泄漏）- 使用 ref 获取最新值
    if (videosRef.current && videosRef.current.length > 0) {
      videosRef.current.forEach(video => {
        if (video && video.previewUrl) {
          URL.revokeObjectURL(video.previewUrl);
        }
      });
    }
    if (previewVideoRef.current && previewVideoRef.current.previewUrl) {
      URL.revokeObjectURL(previewVideoRef.current.previewUrl);
    }
    
    // 清理封面和海报的预览URL
    if (coverPreview) {
      // coverPreview 是 base64 字符串，不需要 revokeObjectURL
      // 但需要重置状态
    }
    if (posterPreview) {
      // posterPreview 是 base64 字符串，不需要 revokeObjectURL
      // 但需要重置状态
    }
    
    // 重置所有上传相关的状态
    setCoverImage(null);
    setCoverPreview('');
    setPosterImage(null);
    setPosterPreview('');
    setVideos([]);
    setPreviewVideo(null);
    setDraggedIndex(null);
    setUploading(false);
    setUploadDialogVisible(false);
    setCurrentTask('');
    setTaskProgress(0);
    setTotalTasks(0);
    setCompletedTasks(0);
    setUploadPhase('idle');
    setUploadedPaths({
      coverPath: '',
      posterPath: '',
      videoPaths: []
    });
    
    // 清空 ref 中的值
    videosRef.current = [];
    previewVideoRef.current = null;
    
    console.log('状态重置完成');
  };

  useEffect(() => {
    // 当路由切换到上传课程页面时，每次都重置所有状态，不保留任何之前的数据
    if (location.pathname === '/main/upload-course') {
      console.log('进入上传课程页面，重置所有状态');
      
      // 无论什么情况，都先重置所有状态
      resetAllStates();
      
      // 从路由 state 获取课程数据
      if (location.state && location.state.courseData) {
        const newCourseData = location.state.courseData;
        // 尝试多种方式获取课程ID
        const currentCourseId = newCourseData?.courseData || newCourseData?.insertId || newCourseData?.id || newCourseData?._id;
        
        console.log('接收到的课程数据:', location.state);
        console.log('课程ID:', currentCourseId);
        
        // 设置新的课程数据
        setCourseData(location.state);
        prevCourseDataRef.current = newCourseData;
      } else {
        // 如果没有 state，说明可能是直接访问
        console.log('没有课程数据');
        setCourseData(null);
        prevCourseDataRef.current = null;
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [location.pathname, location.state]);

  // 处理封面图片选择
  const handleCoverChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      // 验证文件类型
      if (!file.type.startsWith('image/')) {
        alert('请选择图片文件');
        return;
      }
      
      setCoverImage(file);
      
      // 生成预览
      const reader = new FileReader();
      reader.onloadend = () => {
        setCoverPreview(reader.result);
      };
      reader.readAsDataURL(file);
    }
  };

  // 处理海报图片选择
  const handlePosterChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      // 验证文件类型
      if (!file.type.startsWith('image/')) {
        alert('请选择图片文件');
        return;
      }
      
      setPosterImage(file);
      
      // 生成预览
      const reader = new FileReader();
      reader.onloadend = () => {
        setPosterPreview(reader.result);
      };
      reader.readAsDataURL(file);
    }
  };

  // 处理视频选择
  const handleVideoChange = (e) => {
    const files = Array.from(e.target.files);
    
    // 验证文件类型
    const validVideos = [];
    for (let file of files) {
      if (!file.type.startsWith('video/')) {
        alert(`${file.name} 不是视频文件，已跳过`);
        continue;
      }
      
      // 为每个视频创建对象，包含文件、标题和预览 URL
      const previewUrl = URL.createObjectURL(file);
      validVideos.push({
        file: file,
        title: '', // 默认空标题，用户可以后续填写
        previewUrl: previewUrl
      });
    }
    
    const newVideos = [...videos, ...validVideos];
    setVideos(newVideos);
    videosRef.current = newVideos; // 同步更新 ref
  };

  // 删除视频
  const handleRemoveVideo = (index) => {
    const videoToRemove = videos[index];
    
    // 释放预览 URL
    if (videoToRemove.previewUrl) {
      URL.revokeObjectURL(videoToRemove.previewUrl);
    }
    
    // 如果删除的是正在预览的视频，关闭预览
    if (previewVideo === videoToRemove) {
      setPreviewVideo(null);
    }
    
    const newVideos = videos.filter((_, i) => i !== index);
    setVideos(newVideos);
  };

  // 更新视频标题
  const handleVideoTitleChange = (index, title) => {
    const newVideos = [...videos];
    newVideos[index] = {
      ...newVideos[index],
      title: title
    };
    setVideos(newVideos);
    videosRef.current = newVideos; // 同步更新 ref
  };

  // 预览视频
  const handlePreviewVideo = (video) => {
    setPreviewVideo(video.file || video); // 兼容新旧数据结构
  };

  // 关闭预览
  const handleClosePreview = () => {
    setPreviewVideo(null);
  };

  // 同步 videos 状态到 ref
  useEffect(() => {
    videosRef.current = videos;
  }, [videos]);

  // 同步 previewVideo 状态到 ref
  useEffect(() => {
    previewVideoRef.current = previewVideo;
  }, [previewVideo]);

  // 组件卸载时清理所有预览 URL
  useEffect(() => {
    return () => {
      // 使用 ref 获取最新值进行清理
      videosRef.current.forEach(video => {
        if (video.previewUrl) {
          URL.revokeObjectURL(video.previewUrl);
        }
      });
      if (previewVideoRef.current && previewVideoRef.current.previewUrl) {
        URL.revokeObjectURL(previewVideoRef.current.previewUrl);
      }
    };
  }, []);

  // 拖拽开始
  const handleDragStart = (e, index) => {
    setDraggedIndex(index);
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/html', e.currentTarget);
  };

  // 拖拽经过
  const handleDragOver = (e, index) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';

    if (draggedIndex === null || draggedIndex === index) {
      return;
    }

    // 交换位置
    const newVideos = [...videos];
    const draggedVideo = newVideos[draggedIndex];
    
    // 移除拖拽的元素
    newVideos.splice(draggedIndex, 1);
    // 插入到新位置
    newVideos.splice(index, 0, draggedVideo);
    
    setVideos(newVideos);
    setDraggedIndex(index);
  };

  // 拖拽结束
  const handleDragEnd = () => {
    setDraggedIndex(null);
  };

  // 调用接口更新课程信息
  // 参数直接传递，避免依赖异步状态更新
  const handleUpdateCourse = async (coverPath, posterPath, videoPaths, courseTitles) => {
    try {
      setUploadPhase('updating');
      setCurrentTask('更新课程信息中');
      setTaskProgress(100);

      // 获取课程ID，使用多种方式兼容（与 EditCourse 保持一致）
      const courseId = courseData.courseData || courseData.insertId || courseData.id || courseData._id;
      const userInfo = userStorage.getUserInfo();
      if (!userInfo) {
        alert('未获取到用户信息，请重新登录');
        navigate('/login');
        return;
      }
      const phone = userInfo.phone;

      const courseUpdateData = {
        teacherPhone: phone,
        courseName: courseData.courseName,
        courseDesc: courseData.courseIntro,
        courseMembers: courseData.studentPhones || [],
        courseThumb: coverPath,
        courseVideos: videoPaths,
        courseTitles: courseTitles || [],
      };

      // 如果上传了海报，添加到更新数据中
      if (posterPath) {
        courseUpdateData.coursePoster = posterPath;
      }

      console.log('准备更新课程，参数:', { insertId: courseId, course: courseUpdateData });
      
      await api.course.updateCourse(courseId, courseUpdateData);
      
      console.log('课程更新成功');
      
      // 保存已上传的路径到状态（用于可能的重试）
      setUploadedPaths({
        coverPath,
        posterPath,
        videoPaths
      });
      
      setUploadPhase('success');
      setUploading(false);
      setUploadDialogVisible(false);

      // 提示成功
      alert('课程创建并上传成功！');

      // 返回课程管理页面
      navigate('/main/course', { replace: true });

    } catch (error) {
      console.error('更新课程信息失败:', error);
      
      // 保存已上传的路径到状态，以便重试
      setUploadedPaths({
        coverPath,
        posterPath,
        videoPaths
      });
      
      setUploadPhase('error');
      
      // 不关闭对话框，让用户可以重试
      if (error instanceof RequestError) {
        setCurrentTask(`更新失败: ${error.message} - 文件已上传，可以重试`);
      } else {
        setCurrentTask(`更新失败: ${error.message || '未知错误'} - 文件已上传，可以重试`);
      }
    }
  };

  // 立即上传（先上传文件到 OSS，再调用接口）
  const handleUpload = async () => {
    // 验证
    if (!coverImage) {
      alert('请上传封面图片');
      return;
    }
    if (videos.length === 0) {
      alert('请至少上传一个视频');
      return;
    }
    
    // 验证所有视频都有标题
    const videosWithoutTitle = [];
    videos.forEach((video, index) => {
      if (!video.title || !video.title.trim()) {
        videosWithoutTitle.push(index + 1);
      }
    });
    if (videosWithoutTitle.length > 0) {
      alert(`请为第 ${videosWithoutTitle.join('、')} 个视频填写标题`);
      return;
    }

    setUploading(true);
    setUploadDialogVisible(true);
    setUploadPhase('uploading');

    try {
      // 获取课程ID和用户手机号（使用多种方式兼容，与 EditCourse 保持一致）
      const courseId = courseData.courseData || courseData.insertId || courseData.id || courseData._id;
      const userInfo = userStorage.getUserInfo();
      if (!userInfo) {
        alert('未获取到用户信息，请重新登录');
        navigate('/login');
        return;
      }
      const phone = userInfo.phone;

      console.log('开始上传文件...');
      console.log('课程ID:', courseId);
      console.log('用户手机号:', phone);
      console.log('封面图片:', coverImage.name);
      console.log('海报图片:', posterImage ? posterImage.name : '无');
      console.log('视频数量:', videos.length);

      // 设置总任务数：1个封面图片 + 是否有海报 + N个视频
      let totalTaskCount = 1 + videos.length;
      if (posterImage) totalTaskCount += 1;
      setTotalTasks(totalTaskCount);
      setCompletedTasks(0);

      let completedCount = 0;

      // 1. 上传封面图片
      setCurrentTask('封面图片上传中');
      setTaskProgress(0);
      
      const coverPath = await uploadCoverImage(
        coverImage,
        phone,
        courseId,
        (progress) => {
          setTaskProgress(progress * 100);
        }
      );
      
      completedCount += 1;
      setCompletedTasks(completedCount);
      console.log('封面图片上传成功:', coverPath);

      // 2. 上传海报图片（如果有）
      let posterPath = '';
      if (posterImage) {
        setCurrentTask('海报图片上传中');
        setTaskProgress(0);
        
        posterPath = await uploadPosterImage(
          posterImage,
          phone,
          courseId,
          (progress) => {
            setTaskProgress(progress * 100);
          }
        );
        
        completedCount += 1;
        setCompletedTasks(completedCount);
        console.log('海报图片上传成功:', posterPath);
      }

      // 3. 依次上传视频
      const videoPaths = [];
      for (let i = 0; i < videos.length; i++) {
        setCurrentTask(`视频 ${i + 1} 上传中`);
        setTaskProgress(0);
        
        // videos[i] 现在是对象，需要取 file 属性
        const videoFile = videos[i].file || videos[i]; // 兼容新旧数据结构
        const videoPath = await uploadVideo(
          videoFile,
          phone,
          courseId,
          i,
          (progress) => {
            setTaskProgress(progress * 100);
          }
        );
        
        videoPaths.push(videoPath);
        completedCount += 1;
        setCompletedTasks(completedCount);
        console.log(`视频 ${i + 1} 上传成功:`, videoPath);
      }

      setUploadPhase('uploaded');
      console.log('所有文件上传完成，准备更新课程信息');
      console.log('上传的文件路径 - 封面:', coverPath);
      console.log('上传的文件路径 - 海报:', posterPath || '未上传');
      console.log('上传的文件路径 - 视频:', videoPaths);

      // 提取视频标题数组（按照视频顺序，与 videoPaths 顺序一致）
      const courseTitles = videos.map(video => video.title || '');
      console.log('视频标题数组:', courseTitles);

      // 4. 调用接口更新课程信息（直接传递路径参数，避免状态异步问题）
      await handleUpdateCourse(coverPath, posterPath, videoPaths, courseTitles);

    } catch (error) {
      setUploading(false);
      setUploadDialogVisible(false);
      setUploadPhase('idle');
      
      if (error instanceof RequestError) {
        console.error('文件上传失败:', error.message);
        alert(`上传失败: ${error.message}`);
      } else {
        console.error('文件上传失败:', error);
        alert(`上传失败: ${error.message || '未知错误'}`);
      }
    }
  };
  
  // 重试更新课程信息
  const handleRetryUpdate = async () => {
    if (uploadPhase !== 'error') {
      return;
    }
    // 从状态中获取已上传的路径进行重试
    console.log('重试更新课程信息，使用已上传的文件路径');
    // 提取当前 videos 的标题数组
    const courseTitles = videos.map(video => video.title || '');
    await handleUpdateCourse(uploadedPaths.coverPath, uploadedPaths.posterPath, uploadedPaths.videoPaths, courseTitles);
  };

  // 如果没有课程数据，显示提示信息
  if (!courseData) {
    return (
      <div className="upload-course-container">
        <div className="upload-course-box">
          <div style={{ textAlign: 'center', padding: '60px 20px' }}>
            <h3 style={{ color: '#666', marginBottom: '20px' }}>请先创建课程基本信息</h3>
            <p style={{ color: '#999', marginBottom: '30px' }}>
              请从课程管理页面点击"新建课程"按钮开始创建课程
            </p>
            <button
              className="submit-btn"
              onClick={() => navigate('/main/course', { replace: true })}
            >
              返回课程管理
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="upload-course-container">
      <div className="upload-course-box">
        <h2>上传课程</h2>
        
        <div className="course-info-section">
          <h3>课程信息</h3>
          <div className="info-item">
            <span className="label">课程ID：</span>
            <span className="value">{courseData.courseData || 'N/A'}</span>
          </div>
          <div className="info-item">
            <span className="label">课程名称：</span>
            <span className="value">{courseData.courseName}</span>
          </div>
          <div className="info-item">
            <span className="label">课程简介：</span>
            <span className="value">{courseData.courseIntro}</span>
          </div>
          {courseData.studentPhones && courseData.studentPhones.length > 0 && (
            <div className="info-item">
              <span className="label">参课学生：</span>
              <span className="value">{courseData.studentPhones.length}人</span>
            </div>
          )}
        </div>

        <div className="upload-section">
          <div className="form-group">
            <label className="required">封面图片</label>
            <div className="upload-area">
              <input
                type="file"
                id="cover-upload"
                accept="image/*"
                onChange={handleCoverChange}
                style={{ display: 'none' }}
              />
              <label htmlFor="cover-upload" className="upload-btn">
                {coverPreview ? '重新选择' : '选择封面图片'}
              </label>
              {coverPreview && (
                <div className="cover-preview">
                  <img src={coverPreview} alt="封面预览" />
                  <div className="cover-info">{coverImage.name}</div>
                </div>
              )}
            </div>
            <div className="upload-tip">支持 JPG、PNG 格式，大小不超过 5MB</div>
          </div>

          <div className="form-group">
            <label>海报图片</label>
            <div className="upload-area">
              <input
                type="file"
                id="poster-upload"
                accept="image/*"
                onChange={handlePosterChange}
                style={{ display: 'none' }}
              />
              <label htmlFor="poster-upload" className="upload-btn">
                {posterPreview ? '重新选择' : '选择海报图片'}
              </label>
              {posterPreview && (
                <div className="cover-preview">
                  <img src={posterPreview} alt="海报预览" />
                  <div className="cover-info">{posterImage.name}</div>
                </div>
              )}
            </div>
            <div className="upload-tip">支持 JPG、PNG 格式，大小不超过 5MB</div>
          </div>

          <div className="form-group">
            <label className="required">课程视频</label>
            <div className="upload-area">
              <input
                type="file"
                id="video-upload"
                accept="video/*"
                multiple
                onChange={handleVideoChange}
                style={{ display: 'none' }}
              />
              <label htmlFor="video-upload" className="upload-btn">
                + 选择视频文件
              </label>
            </div>
            <div className="upload-tip">支持 MP4、AVI、MOV 等格式，单个文件不超过 100MB</div>
            
            {videos.length > 0 && (
              <div className="video-list">
                <div className="list-header">
                  已选择 {videos.length} 个视频
                  <span className="drag-tip">（可拖动排序）</span>
                </div>
                {videos.map((video, index) => {
                  const videoFile = video.file || video; // 兼容新旧数据结构
                  return (
                    <div
                      key={index}
                      className={`video-item ${draggedIndex === index ? 'dragging' : ''}`}
                      draggable="true"
                      onDragStart={(e) => handleDragStart(e, index)}
                      onDragOver={(e) => handleDragOver(e, index)}
                      onDragEnd={handleDragEnd}
                    >
                      <span className="drag-handle">
                        <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
                          <circle cx="4" cy="4" r="1.5"/>
                          <circle cx="4" cy="8" r="1.5"/>
                          <circle cx="4" cy="12" r="1.5"/>
                          <circle cx="12" cy="4" r="1.5"/>
                          <circle cx="12" cy="8" r="1.5"/>
                          <circle cx="12" cy="12" r="1.5"/>
                        </svg>
                      </span>
                      <span className="video-index">{index + 1}</span>
                      <div className="video-info-group">
                        <span className="video-name">{videoFile.name}</span>
                        <div className="video-title-wrapper">
                          <input
                            type="text"
                            className={`video-title-input ${!video.title || !video.title.trim() ? 'required-empty' : ''}`}
                            placeholder="请输入视频标题（必填）"
                            value={video.title || ''}
                            onChange={(e) => handleVideoTitleChange(index, e.target.value)}
                            maxLength="50"
                          />
                          {(!video.title || !video.title.trim()) && (
                            <span className="required-mark">*</span>
                          )}
                        </div>
                      </div>
                      <span className="video-size">
                        {(videoFile.size / 1024 / 1024).toFixed(2)} MB
                      </span>
                      <button
                        className="preview-video-btn"
                        onClick={() => handlePreviewVideo(video)}
                      >
                        预览
                      </button>
                      <button
                        className="remove-video-btn"
                        onClick={() => handleRemoveVideo(index)}
                      >
                        删除
                      </button>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </div>

        <div className="form-actions">
          <button
            type="button"
            className="cancel-btn"
            onClick={() => {
              if (window.confirm('确定要取消吗？课程已创建，但文件未上传。')) {
                navigate('/main/course', { replace: true });
              }
            }}
          >
            取消
          </button>
          <button
            type="button"
            className="submit-btn"
            onClick={handleUpload}
            disabled={uploading}
          >
            {uploading ? '创建中...' : '立即上传'}
          </button>
        </div>
      </div>

      {/* 上传进度对话框 */}
      <UploadDialog
        visible={uploadDialogVisible}
        currentTask={currentTask}
        progress={taskProgress}
        totalTasks={totalTasks}
        completedTasks={completedTasks}
        phase={uploadPhase}
        onRetry={handleRetryUpdate}
        onCancel={() => {
          setUploadDialogVisible(false);
          setUploading(false);
          alert('文件已上传成功，但课程信息未保存。请在课程管理页面编辑该课程重新保存。');
          navigate('/main/course', { replace: true });
        }}
      />

      {/* 视频预览弹窗 */}
      {previewVideo && (
        <div className="video-preview-modal" onClick={handleClosePreview}>
          <div className="video-preview-content" onClick={(e) => e.stopPropagation()}>
            <div className="preview-header">
              <h3>{(previewVideo.file || previewVideo).name}</h3>
              <button className="close-preview-btn" onClick={handleClosePreview}>
                ✕
              </button>
            </div>
            <video
              className="preview-video"
              src={previewVideo.previewUrl || (previewVideo.file && previewVideo.file.previewUrl)}
              controls
              autoPlay
            />
            <div className="preview-info">
              <span>大小: {((previewVideo.file || previewVideo).size / 1024 / 1024).toFixed(2)} MB</span>
              <span>类型: {(previewVideo.file || previewVideo).type}</span>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export default UploadCourse;

